package constants.session;

import constants.session.Session;
import play.PlayPlugin;
import play.mvc.Http;

import java.lang.reflect.Method;


/**
 * 用于将sessionid写回cookie里
 */
public class SessionPlugin extends PlayPlugin {

    /**
     * Called before an 'action' invocation,
     * ie an HTTP request processing.
     */
    @Override
    public void beforeActionInvocation(Method actionMethod) {
        Session.current.set(new Session());
    }

    @Override
    public void afterActionInvocation() {
        Session session = Session.current();
        if(session.isNewSession() || !session.isCookieless()){
            Http.Response response = Http.Response.current();
            if(response != null){
                //设置P3P头，允许IE在iframe里写入cookies
                //具体请参考：http://yugenning.iteye.com/blog/1236381
                //           http://www.cnblogs.com/_franky/archive/2011/03/16/1985954.html
                response.setHeader("P3P", "CP=CAO PSA OUR");
                //设置httpOnly属性为true，禁止前端拿取cookie(防止xss注入)
                response.setCookie(Session.SESSION_ID_KEY, session.getId(), null, "/", null, false, true);
                response.setCookie(Session.UUID_ID_KEY, session.getUuId(), null, "/", null, false, true);
            }
        }
    }
}